package com.wb.adutils.tools

import android.content.Context
import android.content.SharedPreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

class SPUtil private constructor(val context: Context) {

    companion object : SingletonHolder<SPUtil, Context>(::SPUtil) {
        private const val KEY_OAID_VALUE = "oaid_value"
        private const val KEY_FIRST_LOAD = "first_load"
        private const val KEY_IS_NEXT_START_CLEAR_AD = "KEY_IS_NEXT_START_CLEAR_AD"
    }

    // 是否第一次加载，默认true
    var isFirstLoad: Boolean by PreferenceDelegate(context, KEY_FIRST_LOAD, true)
    var isNextStartClearAd: Boolean by PreferenceDelegate(context, KEY_IS_NEXT_START_CLEAR_AD, false)

    fun clear() {
        PreferenceDelegate(context, "", 0L).clear()
    }

    @Suppress("UNCHECKED_CAST")
    class PreferenceDelegate<T>(context: Context, private val propName: String, private val defaultValue: T) : ReadWriteProperty<Any, T> {

        private val sharedPreferences: SharedPreferences by lazy {
            context.getSharedPreferences(
                "day_video_sp",
                Context.MODE_PRIVATE
            )
        }

        fun clear() {
            sharedPreferences.edit().clear().apply()
        }

        override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
            value?.let { putSPValue(propName, value) }
        }

        override fun getValue(thisRef: Any, property: KProperty<*>): T {
            return getSPValue(propName, defaultValue) ?: defaultValue
        }

        private fun <T> getSPValue(name: String, defaultValue: T): T? = with(sharedPreferences) {
            val result = when (defaultValue) {
                is String -> getString(name, defaultValue)
                is Int -> getInt(name, defaultValue)
                is Long -> getLong(name, defaultValue)
                is Float -> getFloat(name, defaultValue)
                is Boolean -> getBoolean(name, defaultValue)
                else -> null
            }
            result as T
        }

        private fun <T> putSPValue(name: String, value: T) = with(sharedPreferences.edit()) {
            when (value) {
                is Long -> putLong(name, value)
                is String -> putString(name, value)
                is Int -> putInt(name, value)
                is Boolean -> putBoolean(name, value)
                is Float -> putFloat(name, value)
                else -> null
            }
        }?.apply()
    }

}

